var map, circle, handler, _CarTrack, markerTool, localsearch;
export var markerList;
/*测点格式位置*/
export const pointInfo = {
  id: undefined,
  icon: undefined,
  name: undefined,
  label: undefined,
  code: undefined,
  type: undefined,
  pointType: undefined,
  point: [],
  address: undefined,
  txt: undefined,
  eventName: undefined,
  expand: undefined,
}
const ICONS = {
  startIcon: require('@/assets/images/Frame.png'),
  endIcon: require('@/assets/images/Frame-2.png'),
  carIcon: require('@/assets/images/Frame.png'),
};

/*初始化 返回地图对象*/
const initMap = (mapObj) => {
  map = new T.Map(mapObj.id);
  map.centerAndZoom(new T.LngLat(mapObj.centerPoint[0], mapObj.centerPoint[1]), mapObj.zoom);


  //创建缩放平移控件对象
  let control = new T.Control.Zoom();
  //添加缩放平移控件
  map.addControl(control);
  control.setPosition(T_ANCHOR_BOTTOM_RIGHT);
  markerList = []
  return map;
}

const maps = {
  /*初始化地图*/
  init(mapObj) {
    return initMap(mapObj);
  },
  /*注册地图点击事件*/
  mapClick(fun) {
    map.removeEventListener('click')
    map.addEventListener("click", (e) => {
      fun(e)
    });
  },
  /*删除所有标记*/
  deletePoint() {

    map.clearOverLays()
    // this.StartAndStop('clear')
    if (_CarTrack) {
      _CarTrack.clear();
    }
  },
  /*跳转视角*/
  JumpLocation(point) {
    map.panTo(new T.LngLat(point[0], point[1]));
  },
  /*创建标点*/
  CreatePoint: {
    /*在地图上创建标点*/
    CreateMap() {
      markerTool = new T.MarkTool(map, { follow: true });
      markerTool.removeEventListener('mouseup')
      markerTool.addEventListener('mouseup', (e) => {
        let v = e.currentLnglat
        let p = { ...pointInfo }
        p.point = [v.lat, v.lng]
        p.pointType = 'point'
        markerList.push(p)
      })
      markerTool.open()
    },
    /*添加标点*/
    addPoint(point) {
      let p = new T.LngLat(point.point[0], point.point[1])
      let mk = new T.Marker(p);// 创建标注
      map.addOverLay(mk);// 将标注添加到地图中
      if (point.txt) {
        let label = new T.Label({
          text: point.txt,
          position: mk.getLngLat(),
          offset: new T.Point(3, -30)
        });
        map.addOverLay(label);
      }
    }
  },
  /*地图放大 或缩小  true 放大 false缩小*/
  ZoomIn(v) {
    if (v) {
      map.zoomIn()
    } else {
      map.zoomOut()
    }
  },
  /*创建搜索*/
  QeruObj: {
    /*创建搜索  接收 分页*/
    CreateQuery(fun, pageSize) {
      localsearch = new T.LocalSearch(map, {
        pageCapacity: pageSize,
        onSearchComplete: (rtn) => {
          fun(rtn)
        }
      });
      return localsearch
    },
    /*搜索*/
    Query(address) {
      localsearch.search(address);
    },
    /*分页查询*/
    Pages(page) {
      localsearch.gotoPage(page)
    }
  },
  /*工具*/
  Unit: {
    /*开始测量*/
    openLineTool(fun) {
      if (handler) handler.close()
      handler = new T.PolylineTool(map, { showLabel: true });
      handler.open()
      handler.removeEventListener('draw')
      handler.addEventListener('draw', (e) => {
        fun(e)
      })
    },
    /*绘制多边形*/
    polygon(fun) {
      if (handler) handler.close();
      handler = new T.PolygonTool(map);
      handler.open();
      handler.removeEventListener('draw')
      handler.addEventListener('draw', (e) => {
        fun(e)
      })
    },
    /*绘制矩形*/
    openRectangle(fun) {
      let that = this
      if (handler) handler.close();
      handler = new T.RectangleTool(map, { follow: true });
      handler.open();
      handler.removeEventListener('draw')
      handler.addEventListener('draw', (e) => {
        fun(e)
      })
    },
    /*矩形获取范围内的所有坐标*/
    isRectangleTool(sw, ne, mkList) {
      let arr = []
      mkList.forEach(x => {
        let item = x.point
        if (item[0] <= sw.lat
          && item[1] <= sw.lng
          && item[0] >= ne.lat
          && item[1] >= ne.lng
        ) {
          arr.push(x)
        }
      })
      return arr
    },
    /*多边形判断坐标是否在范围内*/
    isPointInPolygon(point, polygon) {
      const [px, py] = point;
      let inside = false;
      for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const [xi, yi] = polygon[i];
        const [xj, yj] = polygon[j];
        const intersect = ((yi > py) !== (yj > py)) && (px < (xj - xi) * (py - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
      }
      return inside;
    },
    drawPolygon(points) {
      //创建面对象
      var polygon = new T.Polygon(points, {
        color: "blue", weight: 3, opacity: 0.5, fillColor: "#FFFFFF", fillOpacity: 0.5
      });
      //向地图上添加面
      map.addOverLay(polygon);
    },
  },
  Trajectory: {
    Create(points, fun, options = {}) {
      const {
        showStartEnd = true,        // 是否显示起止图标
        carIconUrl = ICONS.carIcon, // 小车图标
        startIconUrl = ICONS.startIcon,
        endIconUrl = ICONS.endIcon,
      } = options;

      // if (!points || points.length < 2) {
      //   console.warn('轨迹点不足，无法创建');
      //   return null;
      // }
      let p = points.map(item => new T.LngLat(item[0], item[1]));

      if (p.length > 0) {
        map.panTo(p[0]);
      }

      // 保存起止点图标引用
      let startMarker = null;
      let endMarker = null;

      // 添加起止图标（可选）
      if (showStartEnd) {
        startMarker = new T.Marker(p[0], {
          icon: new T.Icon({
            iconUrl: startIconUrl,
            iconSize: new T.Point(44, 34),
            iconAnchor: new T.Point(12, 31)
          })
        });

        //设置信息窗口内容（可配置）
        const infoHtml = options.startInfoHtml || `
          <div style="font-size:14px;line-height:24px;">
            <strong>电话号码：</strong>${options.trackId || '未知'}
          </div>
        `;
        // <br>
        //     <strong>开始时间：</strong>${options.startTime || '未知'}

        //创建信息窗口
        const infoWindow = new T.InfoWindow(infoHtml, {
          autoPan: true,
          size: new T.Point(220, 80) // 可选：设置窗口大小
        });

        // startMarker.openInfoWindow(infoWindow);
        startMarker.addEventListener("mouseover", function () {
          startMarker.openInfoWindow(infoWindow);
        });


        map.addOverLay(startMarker);

        endMarker = new T.Marker(p[p.length - 1], {
          icon: new T.Icon({
            iconUrl: endIconUrl,
            iconSize: new T.Point(44, 34),
            iconAnchor: new T.Point(12, 31)
          })
        });
        map.addOverLay(endMarker);
      }

      if (_CarTrack) _CarTrack.clear();
      _CarTrack = new T.CarTrack(map, {
        interval: 5,
        speed: 10,
        dynamicLine: true,
        polylinestyle: { color: "#2C64A7", weight: 5, opacity: 0.9 },
        Datas: p,
        passOneNode: (point, index, length) => {
          if (fun) fun(point, index, length);
        }
      });
    },

    createPointList(points, timeArray) {
      points.forEach((point, index) => {
        const [lng, lat] = point;
        const time = timeArray[index];
        const circle = new T.Circle(
          new T.LngLat(lng, lat),
          15,
          {
            color: "orange",
            weight: 5,
            opacity: 0.5,
            fillColor: "#db1f1f",
            fillOpacity: 1
          }
        );

        map.addOverLay(circle);

        circle.addEventListener("mouseover", (e) => {
          const content = `
            经度：${lng.toFixed(6)}<br>
            纬度：${lat.toFixed(6)}<br>
            时间：${time}
          `;
          this.openInfo(content, e);
        });
      });
    },

    // ✅ 修复后的 openInfo
    openInfo(content, e) {
      var point = e.lnglat;
      var infoWindow = new T.InfoWindow(content, { offset: new T.Point(0, -30) });
      map.openInfoWindow(infoWindow, point);
    },


    StartAndStop(type) {
      if (!_CarTrack) return;
      switch (type) {
        case 'start': _CarTrack.start(); break;
        case 'pause': _CarTrack.pause(); break;
        case 'stop': _CarTrack.stop(); break;
        case 'clear':
          _CarTrack.clear();
          break;
      }
    }
  }
  // 修改 Trajectory 模块
  // 🌟 添加图标配置

  // Trajectory: {
  //   instances: [], // 存储所有轨迹实例 { track, startMarker, endMarker }

  //   /**
  //    * 创建轨迹
  //    * @param {Array} points - 轨迹点 [[lng, lat], ...]
  //    * @param {Function} callback - 经过每个点的回调
  //    * @param {Object} options - 额外配置（可选）
  //    */
  //   Create(points, callback, options = {}) {
  //     const {
  //       showStartEnd = true,        // 是否显示起止图标
  //       carIconUrl = ICONS.carIcon, // 小车图标
  //       startIconUrl = ICONS.startIcon,
  //       endIconUrl = ICONS.endIcon,
  //       lineColor = "#2C64A7",
  //       lineWidth = 5,
  //       lineOpacity = 0.9,
  //       speed = 8,
  //       interval = 5,
  //       trackId = "未知编号",
  //       startTime = "未知时间"
  //     } = options;

  //     if (!points || points.length < 2) {
  //       console.warn('轨迹点不足，无法创建');
  //       return null;
  //     }

  //     // 转换为 T.LngLat 数组
  //     const lngLats = points.map(item => new T.LngLat(item[0], item[1]));

  //     // 地图视角跳转到起点
  //     map.panTo(lngLats[0]);

  //     // 创建小车图标
  //     const carIcon = new T.Icon({
  //       iconUrl: carIconUrl,
  //       iconSize: new T.Point(24, 24),
  //       iconAnchor: new T.Point(12, 12)
  //     });

  //     // 创建轨迹实例
  //     const track = new T.CarTrack(map, {
  //       interval,
  //       speed,
  //       dynamicLine: true,
  //       Datas: lngLats,
  //       polylinestyle: {
  //         color: lineColor,
  //         weight: lineWidth,
  //         opacity: lineOpacity
  //       },
  //       icon: carIcon, //  添加移动图标
  //       passOneNode: (point, index, length) => {
  //         if (callback) callback(point, index, length);
  //       }
  //     });

  //     // 保存起止点图标引用
  //     let startMarker = null;
  //     let endMarker = null;

  //     // 添加起止图标（可选）
  //     if (showStartEnd) {
  //       startMarker = new T.Marker(lngLats[0], {
  //         icon: new T.Icon({
  //           iconUrl: startIconUrl,
  //           iconSize: new T.Point(44, 34),
  //           iconAnchor: new T.Point(12, 31)
  //         })
  //       });

  //       //设置信息窗口内容（可配置）
  //       const infoHtml = options.startInfoHtml || `
  //         <div style="font-size:14px;line-height:24px;">
  //           <strong>轨迹编号：</strong>${options.trackId || '未知'}<br>
  //           <strong>开始时间：</strong>${options.startTime || '未知'}
  //         </div>
  //       `;

  //       //创建信息窗口
  //       const infoWindow = new T.InfoWindow(infoHtml, {
  //         autoPan: true,
  //         size: new T.Point(220, 80) // 可选：设置窗口大小
  //       });

  //       // 绑定点击事件
  //       // startMarker.addEventListener("click", function () {
  //       //   startMarker.openInfoWindow(infoWindow);
  //       // });


  //       startMarker.addEventListener("mouseover", function () {
  //         startMarker.openInfoWindow(infoWindow);
  //       });


  //       map.addOverLay(startMarker);

  //       endMarker = new T.Marker(lngLats[lngLats.length - 1], {
  //         icon: new T.Icon({
  //           iconUrl: endIconUrl,
  //           iconSize: new T.Point(44, 34),
  //           iconAnchor: new T.Point(12, 31)
  //         })
  //       });
  //       map.addOverLay(endMarker);
  //     }

  //     // 保存实例和相关标记
  //     const instance = { track, startMarker, endMarker };
  //     this.instances.push(instance);

  //     return instance; // 返回以便外部控制
  //   },

  //   /**
  //    * 控制轨迹：start / pause / stop / clear
  //    * @param {'start'|'pause'|'stop'|'clear'} type
  //    * @param {number|null} index - 指定某条轨迹，null 表示全部
  //    */
  //   StartAndStop(type, index = null) {
  //     const actionMap = {
  //       start: 'start',
  //       pause: 'pause',
  //       stop: 'stop',
  //       clear: 'clear'
  //     };

  //     const action = actionMap[type];
  //     if (!action) return;

  //     if (index !== null) {
  //       const item = this.instances[index];
  //       if (item && item.track) {
  //         item.track[action]();
  //       }
  //     } else {
  //       this.instances.forEach(item => {
  //         if (item.track) {
  //           item.track[action]();
  //         }
  //       });
  //     }
  //   },

  //   /**
  //    * 清除所有轨迹及图标
  //    */
  //   clearAll() {
  //     this.instances.forEach(item => {
  //       if (item.track) {
  //         item.track.clear(); // 清除轨迹线和小车
  //       }
  //       if (item.startMarker) map.removeOverLay(item.startMarker);
  //       if (item.endMarker) map.removeOverLay(item.endMarker);
  //     });
  //     this.instances = [];
  //   },

  //   /**
  //    * 获取当前轨迹数量
  //    */
  //   getCount() {
  //     return this.instances.length;
  //   }
  // }


}
export default maps
